package com.freework.report.base.controller;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;

import com.freework.report.base.vo.RequestParam;

public class ReadRequestParam {
   public final static String SCOPE_SESSION="session";
   public final static String SCOPE_REQUEST_ATTR="requestAttr";
   public final static String SCOPE_REQUEST="request";
	String getValue(HttpServletRequest request, HttpSession session,
			String paramsName, String scope) {

		if (scope == null || scope.equals("") || scope.equals(SCOPE_REQUEST))
			return request.getParameter(paramsName);

		String name;
		String valuename = null;
		int index = paramsName.indexOf('.');
		if (index != -1) {
			name = paramsName.substring(0, index);
			valuename = paramsName.substring(index + 1);
		} else {
			name = paramsName;
		}

		Object tmpvalue = null;
		if (SCOPE_SESSION.equals(scope)) {
			tmpvalue = session.getAttribute(name);
		} else if (SCOPE_REQUEST_ATTR.equals(scope)) {
			tmpvalue = request.getAttribute(name);
		}
		String value = null;
		try {
			if (tmpvalue != null)
				value = valuename == null ? tmpvalue.toString() : BeanUtils.getProperty(tmpvalue, valuename);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
		return value;
	}

	Map<String, Map<String, String>> getParamMap(HttpServletRequest request,RequestParam[] requestParams) {
		HttpSession session = request.getSession();
		Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>();
		for (int i = 0; i < requestParams.length; i++) {
			String name = requestParams[i].getName();
			String groupcode = requestParams[i].getGroupcode();
			Map<String, String> values = map.get(groupcode);
			if (values == null) {
				values = new HashMap<String, String>();
				map.put(groupcode, values);
			}
			String value = getValue(request, session, name, requestParams[i].getScope());
			values.put(name, value);

		}
		return map;

	}


}
